<template>
  <uploader
      :options="options"
      :file-status-text="statusText"
      class="uploader-example"
      ref="uploaderRef"
      @file-complete="fileComplete"
      @complete="complete"
  >
  </uploader>



  <a-space direction="horizontal" style="margin-left: 20px">

    <a-button type="primary" @click="triggerFileInput">选择文件或文件夹</a-button>
    <input type="file" ref="fileInput" @change="handleFileChange"hidden="hidden"/>
    <a-button type="primary" @click="handleUploadFolder(0)">上传</a-button>

  </a-space>

</template>

<script>
import { nextTick, ref, onMounted } from 'vue'
import axiosInstance from "@/axios/axios.js";
import {message} from "ant-design-vue";
import { v4 as uuidv4 } from 'uuid';
import JSZip from 'jszip';

class Folder{
  constructor(files){
    if (files.length <= 0){
      return
    }
    this.height = 0;
    this.root = new FolderNode()
    const relativePath = files[0].webkitRelativePath;
    this.folderName = relativePath.split('/')[0];

    files.forEach(file => {
      const path = file.webkitRelativePath || file.name
      const parts = path.split('/')
      if (parts.length > this.height){
        this.height = parts.length
      }
      let current = this.root
      parts.forEach((part, index) => {
        if (index === parts.length - 1) {
          //~$开头的文件是wps的临时文件，不处理。
          if (!part.startsWith('~$')) {
            current.addFile(file)
          }

        } else {
          current.addSubFolder(part)
          current = current.subFolders.get(part)
        }
      })
    })
  }

}
class FolderNode {
  constructor() {
    this.subFolders = new Map;
    this.files = [];
  }
  addSubFolder(folderName) {
    if (!this.subFolders.has(folderName)) {
      // 如果键不存在，则创建新的Folder对象并添加到subFolders中
      let newFolder = new FolderNode();
      this.subFolders.set(folderName, newFolder);
    }
  }
  addFile(file) {
    this.files.push(file);

  }
}
export default {

  data(){
    return{
      files: [],
      folder:{},
      fileSelectMessage:"",
      uploadProgress:0,
      zipFile:null,
      zipReady:false, //zip文件准备好后才能上传按钮生效
      folderName:"",
      compressedFile:null,
      isCompressedFileReady:false,
    }
  },

  methods:{

    async handleUploadFolder(needWatermark) {


      if (!this.isCompressedFileReady) {
        message.warn("ZIP文件还未准备好，请稍候。");
        return;
      }

      const chunkSize = 5 * 1024 * 1024; // 5MB
      const totalChunks = Math.ceil(this.compressedFile.size / chunkSize);
      const fileId = uuidv4();
      const folderName = this.folder.folderName;

      let uploadedChunks = 0;
      const updateProgress = () => {
        uploadedChunks++;
        this.uploadProgress = Math.round((uploadedChunks / totalChunks) * 100);
        console.log("分片上传进度：",this.uploadProgress+"%")
      };

      const uploadChunk = async (chunkIndex) => {
        const start = chunkIndex * chunkSize;
        const end = Math.min(start + chunkSize, this.compressedFile.size);
        const chunk = this.compressedFile.slice(start, end);

        const formData = new FormData();
        formData.append("username", this.$cookies.get("username"));
        formData.append("ifWatermark", 0);
        formData.append("fileId", fileId);
        formData.append("chunkIndex", chunkIndex);
        formData.append("totalChunks", totalChunks);
        formData.append("folderName", this.folderName);
        formData.append("chunk", chunk);

        try {
          await axiosInstance.post("/upload/chunk", formData, {
            headers: {
              "Content-Type": "multipart/form-data",
              Authorization: `Bearer ${this.$cookies.get("jwt")}`
            }
          });
          updateProgress();
        } catch (error) {
          console.error(`上传分片 ${chunkIndex} 失败:`, error);
          throw error;
        }
      };

      const uploadAllChunks = async () => {
        const chunkPromises = [];
        for (let i = 0; i < totalChunks; i++) {
          chunkPromises.push(uploadChunk(i));

          // 每5个请求为一组并发执行
          if (chunkPromises.length === 5 || i === totalChunks - 1) {
            await Promise.all(chunkPromises);
            chunkPromises.length = 0;
          }
        }
      };

      try {
        await uploadAllChunks();
        message.success("文件夹上传成功！");
      } catch (error) {
        message.error("上传失败，请重试。");
      }

    },


    //点击文件上传按钮激活文件input标签
    //文件上传按钮单纯为了好看
    triggerFileInput(){
      this.$refs.fileInput.click();
    },

    handleFileChange(event) {

      this.compressedFile=event.target.files[0];
      this.folderName = this.compressedFile.name
      console.log("folderName:", this.folderName)
      this.isCompressedFileReady=true;

    },

  }
  // setup () {
  //   const uploaderRef = ref(null)
  //   const options = {
  //     target: '//localhost:3000/upload', // '//jsonplaceholder.typicode.com/posts/',
  //     testChunks: false
  //   }
  //   const attrs = {
  //     accept: 'image/*'
  //   }
  //   const statusText = {
  //     success: 'success',
  //     error: 'error',
  //     uploading: 'uploading',
  //     paused: 'paused',
  //     waiting: 'waiting'
  //   }
  //   const complete = () => {
  //     console.log('complete', arguments)
  //   }
  //   const fileComplete = () => {
  //     console.log('file complete', arguments)
  //   }
  //   onMounted(() => {
  //     nextTick(() => {
  //       window.uploader = uploaderRef.value.uploader
  //     })
  //   })
  //   return {
  //     uploaderRef,
  //     options,
  //     attrs,
  //     statusText,
  //     complete,
  //     fileComplete
  //   }
  // }
}
</script>

<style>
.uploader-example {
  width: 880px;
  padding: 15px;
  margin: 40px auto 0;
  font-size: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .4);
}
.uploader-example .uploader-btn {
  margin-right: 4px;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>